package com.tensquare.article.service.impl;


import com.tensquare.article.pojo.Comment;
import com.tensquare.article.repository.CommentRepository;
import com.tensquare.article.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @author BAO
 * @version V1.0
 * @Package com.tensquare.article.service.impl
 * @date 2020/12/3 19:31
 * @description:
 */
@Service
@Slf4j
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Comment findById(String id) {
        log.info("findById");
        return commentRepository.findById(id).get();
    }

    @Override
    public Page<Comment> findAll() {
        log.info("findAll");
        PageRequest pageRequest = new PageRequest(0, 5);
        Page<Comment> all = commentRepository.findAll(pageRequest);
        return all;
    }

    @Override
    public Comment save(Comment comment) {
        log.info("findAll");
        commentRepository.save(comment);
        Comment save = commentRepository.save(comment);
        return save;
    }

    @Override
    public Comment update(Comment comment) {
        log.info("update");
        return commentRepository.save(comment);
    }

    @Override
    public void deleteById(String id) {
        log.info("deleteById");
        commentRepository.deleteById(id);

    }

    @Override
    public List<Comment> findByarticleId(String articleId) {
        return commentRepository.findByArticleid(articleId);
    }

    @Override
    public void getThumbup(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.inc("thumbup",1);
        mongoTemplate.updateFirst(query,update,"comment");
    }
}
